<?php
/**
 * Created by PhpStorm.
 * User: iamya
 * Date: 2017/7/11
 * Time: 17:16
 */

namespace app\home\controller;


use app\common\model\ShopPaymentModel;
use app\common\model\ShopPromotionCardItemModel;
use app\common\model\ShopPromotionCardModel;
use app\common\model\ShopPromotionCardOrderModel;
use Payment\Common\PayException;
use think\Exception;
use think\Request;

class CardController extends BaseController
{
    private $paymentModel;
    private $shopPromotionCardModel;
    private $shopPromotionCardItemModel;
    private $shopPromotionCardOrderModel;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->paymentModel = new ShopPaymentModel();
        $this->shopPromotionCardModel = new ShopPromotionCardModel();
        $this->shopPromotionCardItemModel = new ShopPromotionCardItemModel();
        $this->shopPromotionCardOrderModel = new ShopPromotionCardOrderModel();
    }

    public function index()
    {
        $list = $this->shopPromotionCardModel->getPageList(1);
        $uid = $this->getMemberUid();
        $cardId = $this->shopPromotionCardItemModel->where(['member_uid'=>$uid,'status'=>1])->column('card_id');
        foreach ($list as $index => $value) {
            if (in_array($value['card_id'], $cardId)) {
                $list[$index]['status'] = 0;//已经领过了
            } else {
                $list[$index]['status'] = 1;//没有领过
            }
        }
        if ($this->request->isPost()) {
            return $list;
        }
        $this->assign('list', $list);
        return $this->fetch();
    }
    /*发放优惠券*/
    public function sendfreeCard(){
        $uid = $this->getMemberUid();
        if ($uid < 0) {
            $this->error('请先登录', url('/home/Public/userLogin', ['url' => urlencode($_SERVER['HTTP_REFERER'])]));
        }
        $cardId = $this->request->param('card_id', 0);
        $cardInfo = $this->shopPromotionCardModel->where('card_id', $cardId)->find();
        $this->shopPromotionCardItemModel->restoreInventory($cardId); //清除15分钟卡券
        $order = $this->shopPromotionCardOrderModel->where(['member_uid' => $uid,'status'=>0, 'card_id' => $cardId, 'end_time' => ['>', time()]])->find();
        if (!$order) { //未生成订单
            $itemId = $this->shopPromotionCardModel->sendCard($uid, $cardId); //发放卡券
            if($itemId){
                $this->success('领取成功');
            }else{
                $this->error($this->shopPromotionCardModel->getError());
            }
        }
    }
    /**
     * 购买优惠券
     * @return mixed
     */
    public function sendCard()
    {
        $uid = $this->getMemberUid();
        if ($uid < 0) {
            $this->error('请先登录', url('/home/Public/userLogin', ['url' => urlencode($_SERVER['HTTP_REFERER'])]));
        }
        $device= is_mobile();
        $cardId = $this->request->param('card_id', 0);
        $cardInfo = $this->shopPromotionCardModel->where('card_id', $cardId)->find();
        $this->shopPromotionCardItemModel->restoreInventory($cardId); //清除15分钟卡券
        $order = $this->shopPromotionCardOrderModel->where(['member_uid' => $uid,'status'=>0, 'card_id' => $cardId, 'end_time' => ['>', time()]])->find();
        if (!$this->request->has('openid')&&$device==3&&$cardInfo['send_type']==2) {
            $this->redirect('plus/Wxpay/getOpenid', ['url' => urlencode(get_current_url())]);
            exit();
        }
        //支付方式
        $payment = $this->paymentModel->getList($this->getSiteId());
        if (!$order) { //未生成订单
            $itemId = $this->shopPromotionCardModel->sendCard($uid, $cardId); //发放卡券
            if ($itemId) { //该用户未领过该卡券发放成功
                if ($cardInfo['send_type'] == 2) { //在线购买类型
                    $itemInfo = $this->shopPromotionCardItemModel->where('item_id', $itemId)->find();
                    //添加卡券订单
                    $orderSn = 'card' . rand_number();
                    $orderInfo = [
                        'order_sn' => $orderSn,
                        'card_name' => $cardInfo['title'],
                        'card_id' => $cardId,
                        'member_uid' => $uid,
                        'create_time' => time(),
                        'end_time' => $itemInfo['receive_time'] + 900,
                        'item_id' => $itemId,
                        'order_price' => $cardInfo['sale_money']
                    ];
                    $this->shopPromotionCardOrderModel->addData($orderInfo);
                    $order = $this->shopPromotionCardOrderModel->where('id',$this->shopPromotionCardOrderModel->id)->find();
                } else { //免费卡券领取成功
                    $this->success('领取成功');
                }
            }else{
                $this->error($this->shopPromotionCardModel->getError());
            }
        }
        if ($device == 3) { //微信端需先获取用户openid
            $jsApiParameters = $this->getJsApiParameters($this->request->param('openid'),$order['order_sn'],$device);
            $this->assign('jsApiParameters',$jsApiParameters);
        }
        $this->assign('payment', $payment);
        $this->assign('device', $device); //1、手机端 2电脑端 3微信端
        $this->assign('cardInfo', $cardInfo);
        $this->assign('orderInfo', $order);
        return $this->fetch();

    }

    /**
     * 获取微信内支付参数
     * @param $openid
     * @param $orderSn
     * @param $device
     * @return mixed
     */
    private function getJsApiParameters($openid,$orderSn,$device){
        $param['openid'] = $openid;
        $param['site_id'] = $this->getSiteId();
        $param['order_type'] = 'order';
        $param['order_sn'] = $orderSn;
        $param['device'] = $device;
        $url = url('plus/Wxpay/pay', ['_ajax' => 1], true, true);
        $result = send_http($url, $param, 'POST');
        $result = json_decode($result, true);
        return $result['data'];
    }

}